﻿@{
    ViewData["Title"] = "ABPCodeGenerator";
    ViewBag.PageName = "GenerateCode";
}

<div class="container-fluid">

    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">生成模板<small></small></h1>
    </div>

    <div class="card shadow">
        <div class="card-body">
            <div class="form-group row">
                <label class="col-md-2 col-form-label" for="exampleFormControlSelect1">数据库表</label>
                <select class="col-md-10 form-control" id="SelectDatabaseTableName">
                </select>
            </div>

            <button type="submit" class="btn btn-primary float-right ml-2" id="Generate">生成</button>
            <button type="submit" class="btn btn-primary float-right" id="Search" hidden>查询</button>
        </div>
    </div>


    <div class="card mt-3 shadow">
        <div class="card-body">
            <table class="table table-bordered table-hover w-100" id="Table"></table>
        </div>
    </div>
</div>

@section Scripts
{
    <script>
        var baseUrl = site.app.setting.service.baseUrl;
        var page, localStorageItem = null;

        page = {
            $SelectDatabaseTableName: $("#SelectDatabaseTableName"),
            $SelectedDatabaseTableName: $("#SelectDatabaseTableName option:selected"),
            $Search: $("#Search"),
            $Generate: $("#Generate"),
            $Table: $("#Table"),
            DataTable: null,
            SelectedArray: [],//存放当前表格中选择的项的ColumnId集合

            ListDatabaseTableName: function () {

                $.post(baseUrl + "/ListDatabaseTableName", { connectionString: localStorageItem.ConnectionString }, function (result) {
                    if (result.errorCode === site.app.setting.service.noneErrorCode) {

                        //填充数据到下拉组件

                        var targetdbname = localStorageItem.TableName;

                        for (var i = 0; i < result.data.length; i++) {

                            var selected = targetdbname === result.data[i].text ? "selected" : "";

                            var option = "<option id=" + result.data[i].id + " " + selected + ">" + result.data[i].text + "</option>";

                            page.$SelectDatabaseTableName.append(option);

                        }

                        page.Search();

                    } else {
                        site.app.notify.error(result.errorMessage);
                    }
                })
            },

            Search: function () {

                if ($("#SelectDatabaseTableName option:selected").val() === "") {

                    site.app.notify.error("请选择一个数据库表");

                    return;
                }

                page.LoadSelectedDatabaseTableInfo($("#SelectDatabaseTableName option:selected").val())

            },

            LoadSelectedDatabaseTableInfo: function (databaseTableName) {

                $.post(baseUrl + "/ListDatabaseTableColumn", { connectionString: localStorageItem.ConnectionString, tableName: databaseTableName }, function (result) {
                    if (result.errorCode === site.app.setting.service.noneErrorCode) {

                        //将数据填充给到表中
                        if (page.DataTable) {
                            page.DataTable.fnDestroy();
                            page.$Table.empty();
                        }

                        page.DataTable = page.$Table.dataTable({
                            "scrollCollapse": true,
                            "scrollX": true,
                            "searching": false,
                            "ordering": false,
                            "renderer": "bootstrap",
                            "destroy": true,
                            "data": $.parseJSON(result.data),
                            "language": {
                                processing: "处理中...",
                                lengthMenu: "每页显示 _MENU_ 项",
                                zeroRecords: "没有匹配结果",
                                info: "第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                                infoEmpty: "显示第 0 至 0 项结果，共 0 项",
                                infoFiltered: "",
                                infoPostFix: "",
                                search: "搜索:",
                                searchPlaceholder: "搜索...",
                                url: "",
                                emptyTable: "表中数据为空",
                                loadingRecords: "载入中...",
                                infoThousands: ",",
                                paginate: {
                                    first: "首页",
                                    previous: "上页",
                                    next: "下页",
                                    last: "末页"
                                },
                                aria: {
                                    paginate: {
                                        first: "首页",
                                        previous: "上页",
                                        next: "下页",
                                        last: "末页"
                                    },
                                    sortAscending: "以升序排列此列",
                                    sortDescending: "以降序排列此列"
                                },
                                decimal: "-",
                                thousands: "."
                            },
                            //"dom": "<'row'<'col-md-12 align-items-center't><'col-md-2 align-items-center'i><'col-md-2 align-items-center'l><'col-md-8 align-items-center'p>>",
                            "dom": '<"top">rt<"row"<"col-md-12"<"float-left"i><"float-right"p><"float-left datatable_l"l>>>',
                            "columns": [
                                {
                                    "title": "RowNumber",
                                    "data": null,
                                    "width": "10px",
                                    "orderable": false,
                                    "render": function (data, type, row, meta) {
                                        return meta.row + 1 + meta.settings._iDisplayStart;
                                    }
                                },
                                {
                                    "title": "是否主键",
                                    "data": "PrimaryKey",
                                    "render": function (data) {
                                        return data === "√" ? "是" : "否";
                                    }
                                },
                                {
                                    "title": "列名",
                                    "data": "ColumnName"
                                },
                                {
                                    "title": '是否作为查询条件',
                                    "data": "IsSearchFiled",
                                    "render": function (data, type, row, meta) {
                                        var checked = data === true ? "checked" : "";

                                        return '<input class="checkbox-item align-middle text-center" type="checkbox" value="' + row.ColumnId + '" ' + checked + '/>';

                                    }
                                },
                                {
                                    "title": '是否审计字段',
                                    "data": "IsAuditFiled",
                                    "render": function (data, type, row, meta) {
                                        var checked = data === true ? "checked" : "";

                                        return '<input class="checkbox-item align-middle text-center" type="checkbox" value="' + row.ColumnId + '" ' + checked + '/>';

                                    }
                                },
                                {
                                    "title": '是否枚举类型',
                                    "data": "IsEnumField",
                                    "render": function (data, type, row, meta) {
                                      var checked = data === true ? "checked" : "";

                                        return '<input class="checkbox-item align-middle text-center" type="checkbox" value="' + row.ColumnId + '" ' + checked + '/>';

                                    }
                                },
                                {
                                    "title": '枚举字段名称',
                                    "data": "EnumFieldName",
                                    "createdCell": function (td, cellData, rowData, row, col) {
                                        var $control = $('<input class="checkbox-item align-middle text-center" type="text" value="' + rowData.ColumnId + '"/>');
                                        $control.appendTo($(td)).click(function () {
                                            page.SelectItem($control, rowData);
                                        });

                                    }
                                },
                                {
                                    "title": '中文多语言',
                                    "data": "MultiLanguage_CN",
                                    "createdCell": function (td, cellData, rowData, row, col) {
                                        var $control = $('<input class="checkbox-item align-middle text-center" type="text" value="' + rowData.ColumnId + '"/>');
                                        $control.appendTo($(td)).click(function () {
                                            page.SelectItem($control, rowData);
                                        });

                                    }
                                },
                                {
                                    "title": '英文多语言',
                                    "data": "MultiLanguage_US",
                                    "createdCell": function (td, cellData, rowData, row, col) {
                                        var $control = $('<input class="checkbox-item align-middle text-center" type="text" value="' + rowData.ColumnName + '"/>');
                                        $control.appendTo($(td)).click(function () {
                                            page.SelectItem($control, rowData);
                                        });

                                    }
                                }
                            ]
                        }).on('draw.dt', function (e, settings) {
                            //页行改变或选择其他页的时候，保持选择
                            page.SelectAll();
                        });

                    } else {
                        site.app.notify.error(result.errorMessage);
                    }
                })

            },

            Generate: function () {

                if (page.SelectedArray.length === 0) {
                    site.app.notify.error("最少选择一个字段");

                    return;
                }

                var databaseTableName = $("#SelectDatabaseTableName option:selected").val();
                localStorageItem.columnIdList = _.pluck(page.SelectedArray, "ColumnId");

                $.post(baseUrl + "/GenerateCode", { input: localStorageItem }, function (result) {
                    if (result.errorCode === site.app.setting.service.noneErrorCode) {
                        site.app.notify.success("生成成功");

                        page.DownloadGeneratedZipFile(result.zipFilePath);
                    } else {
                        site.app.notify.error(result.errorMessage);
                    }
                })
            },

            SelectAll: function () {

                var $self = $(".checkbox-all");
                page.SelectedArray = [];

                if ($self.prop("checked")) {
                    var data = page.DataTable.fnGetData();
                    _.each(data, function (item) {
                        page.SelectedArray.push(item);
                    });
                }

                //界面上体现全选/全不选
                $self.closest(".dataTables_wrapper").find(".checkbox-item").prop("checked", $self.prop("checked"));
            },

            SelectItem: function ($this, item) {

                if ($this.prop("checked")) {
                    if (!_.contains(page.SelectedArray, item)) {
                        page.SelectedArray.push(item);
                    }
                } else {
                    page.SelectedArray = _.reject(page.SelectedArray, function (one) { return one.value === item.ColumnId; });
                }

            },

            LoadLocalStorageItem: function () {
                //获取之前保存到本地浏览器的数据库连接字符串
                var localStorageJson = localStorage.getItem(site.app.setting.localStorageKey.Home);

                if (localStorageJson !== null || localStorageJson !== "") {
                    localStorageItem = JSON.parse(localStorageJson);
                } else {
                    site.app.notify.error("请先在基础配置页面维护配置信息");
                }
            },

            DownloadGeneratedZipFile: function (relativeFilePath) {

                window.location.href = baseUrl + "/DownloadGeneratedZipFile?relativeFilePath=" + relativeFilePath;
            },

            Init: function () {
                page.LoadLocalStorageItem();

                page.$Search.click(function () {
                    page.Search();
                });

                page.$Generate.click(function () {
                    page.Generate();
                });

                page.ListDatabaseTableName();

                $(document).on("click", ".checkbox-all", function () {
                    page.SelectAll();
                });

                page.$SelectDatabaseTableName.on("click", function () {
                    page.Search();
                })

            }
        };

        page.Init();

    </script>
}
